﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.IO;
using System.Text.RegularExpressions;
using System.Reflection;

namespace newTurtle8
{
    partial class SoldierDataForm : UserControl
    {
        static private List<string> cityList = initCityArray();
        private SoldierCard sCard;
        private Company company = Company.getInstance();

        #region Constructors
        public SoldierDataForm()
        {
            InitializeComponent();
            this.Dock = DockStyle.Fill;

            initializeBoxesItems();
            comboBoxCity.Items.AddRange(cityList.ToArray());
        }
        public SoldierDataForm(string armyID) : this()
        {
            Soldier s = company.getSoldier(armyID);

            //PersonalData
            maskedTextBoxArmyId.Text = s.ArmyID;
            maskedTextBoxSocialId.Text = s.SocialID;
            maskedTextBoxFirstName.Text = s.FirstName;
            maskedTextBoxLastName.Text = s.LastName;
            maskedTextBoxHomePhone.Text = s.HomePhone;
            maskedTextBoxCellPhone.Text = s.CellPhone;
            maskedTextBoxEmail.Text = s.Email;
            dateTimePickerBirthDay.Value = s.Birthday;
            comboBoxCity.Text = s.City;
            maskedTextBoxStreet.Text = s.Street;
            numericUpDownBuliding.Value = s.BuildingNum;
            numericUpDownApartment.Value = s.ApartmentNum;
            pictureBox.Image = s.Picture;
            textBoxComments.Text = s.comments;

            //FamilyInfo
            numericUpDownChildren.Value = s.ChildrenCtr;
            textBoxChildrenNames.Text = s.ChildrenNames;
            textBoxWifeName.Text = s.WifeName;
            listBoxCoupleState.SelectedItem = EnumUtils.getHebDescription(s.CoupleStatus);

            //ArmyInfo
            comboBoxPosition.Text = s.Position;
            numericUpDownPlatoon.Value = s.Platoon;
            numericUpDownShoeSize.Text = s.ShoeSize.ToString();
            comboBoxShoeStatus.SelectedItem = EnumUtils.getHebDescription(s.ShoeStatus);
            comboBoxDiscStatus.SelectedItem = EnumUtils.getHebDescription(s.IdDiscStatus);
            dateTimePickerArrival.Value = s.ArrivalDate;

            if (s.IsActive)
                radioButtonIsActiveYes.Checked = true;
            else radioButtonIsActiveNo.Checked = true;

            //ContactInfo
            maskedTextBoxRelativeFirstName.Text = s.ContactFirstName;
            maskedTextBoxRelativeLastName.Text = s.ContactLastName;
            maskedTextBoxRelativeHomePhone.Text = s.ContactHomePhone;
            maskedTextBoxRelativeCellPhone.Text = s.contactCellPhone;
            maskedTextBoxRelativeEmail.Text = s.ContactEmail;
            comboBoxRelation.Text = s.ContactRelation.ToString();
            maskedTextBoxRelativeAdress.Text = s.ContactAdress;

            //Qualifications
            CheckedListBox.ObjectCollection col = checkedListBoxQualifications.Items;
            foreach (string q in s.QualifiedList)
               checkedListBoxQualifications.SetItemChecked(col.IndexOf(q), true);

        }


        #endregion

        #region private methods

        /// <summary>
        /// returns an array of Israeli cities.
        /// </summary>
        /// <returns></returns>
        static private List<string> initCityArray()
        {
            SqlCommand selectCmd = SqlManager.SqlCommandFactory("SELECT city FROM IsraelCities");
            SqlDataReader reader = SqlManager.getSqlDataReader(selectCmd);

            List<string> list = new List<string>();
            while (reader.Read())
                list.Add(reader.GetString(0));

            selectCmd.Connection.Close();
            reader.Close();

            return list;
        }
        private void PaintWithWhiteAllFields()
        {
            maskedTextBoxFirstName.BackColor = Color.White;
            maskedTextBoxLastName.BackColor = Color.White;
            maskedTextBoxArmyId.BackColor = Color.White;
            maskedTextBoxSocialId.BackColor = Color.White;
            maskedTextBoxHomePhone.BackColor = Color.White;
            maskedTextBoxCellPhone.BackColor = Color.White;
            maskedTextBoxEmail.BackColor = Color.White;
            comboBoxCity.BackColor = Color.White;
            maskedTextBoxStreet.BackColor = Color.White;
            numericUpDownBuliding.BackColor = Color.White;
            maskedTextBoxRelativeHomePhone.BackColor = Color.White;
            maskedTextBoxRelativeCellPhone.BackColor = Color.White;
            maskedTextBoxRelativeEmail.BackColor = Color.White;
        }
        private bool PaintWithYellow()
        {
            bool yellow = false;

            if (maskedTextBoxFirstName.Text == string.Empty)
            {
                maskedTextBoxFirstName.BackColor = Color.Yellow;
                yellow = true;
            }
            if (maskedTextBoxLastName.Text == string.Empty)
            {
                maskedTextBoxLastName.BackColor = Color.Yellow;
                yellow = true;
            }
            if ((maskedTextBoxArmyId.Text == string.Empty) ||
                (maskedTextBoxArmyId.errorProvider1.GetError(maskedTextBoxArmyId) != string.Empty))
            {
                maskedTextBoxArmyId.BackColor = Color.Yellow;
                yellow = true;
            }
            if ((maskedTextBoxSocialId.Text == string.Empty) ||
                (maskedTextBoxSocialId.errorProvider1.GetError(maskedTextBoxSocialId) != string.Empty))
            {
                maskedTextBoxSocialId.BackColor = Color.Yellow;
                yellow = true;
            }
            if (maskedTextBoxHomePhone.errorProvider1.GetError(maskedTextBoxHomePhone) != string.Empty)
            {
                maskedTextBoxHomePhone.BackColor = Color.Yellow;
                yellow = true;
            }
            if (maskedTextBoxCellPhone.errorProvider1.GetError(maskedTextBoxCellPhone) != string.Empty)
            {
                maskedTextBoxCellPhone.BackColor = Color.Yellow;
                yellow = true;
            }

            if (maskedTextBoxEmail.errorProvider1.GetError(maskedTextBoxEmail) != string.Empty)
            {
                maskedTextBoxEmail.BackColor = Color.Yellow;
                yellow = true;
            }

            if (maskedTextBoxRelativeHomePhone.errorProvider1.GetError(maskedTextBoxRelativeHomePhone) != string.Empty)
            {
                maskedTextBoxRelativeHomePhone.BackColor = Color.Yellow;
                yellow = true;
            }

            if (maskedTextBoxRelativeCellPhone.errorProvider1.GetError(maskedTextBoxRelativeCellPhone) != string.Empty)
            {
                maskedTextBoxRelativeCellPhone.BackColor = Color.Yellow;
                yellow = true;
            }

            if (maskedTextBoxRelativeEmail.errorProvider1.GetError(maskedTextBoxRelativeEmail) != string.Empty)
            {
                maskedTextBoxRelativeEmail.BackColor = Color.Yellow;
                yellow = true;
            }

            return yellow;

        }

        /// <summary>
        /// creates and sets a soldier instance after, while reading input from the different fields.
        /// </summary>
        /// <returns></returns>
        private Soldier createSoldier()
        {
            Soldier s = new Soldier();

            //PersonalData
            s.FirstName = maskedTextBoxFirstName.Text.Trim();
            s.LastName = maskedTextBoxLastName.Text.Trim();
            s.SocialID = maskedTextBoxSocialId.Text.Trim();
            s.ArmyID = maskedTextBoxArmyId.Text.Trim();
            s.HomePhone = maskedTextBoxHomePhone.Text.Trim();
            s.CellPhone = maskedTextBoxCellPhone.Text.Trim();
            s.Email = maskedTextBoxEmail.Text.Trim();
            s.Birthday = dateTimePickerBirthDay.Value;
            s.City = comboBoxCity.Text.Trim();
            s.Street = maskedTextBoxStreet.Text.Trim();
            s.BuildingNum = (short)numericUpDownBuliding.Value;
            s.ApartmentNum = (short)numericUpDownApartment.Value;
            s.Picture = pictureBox.Image;
            s.comments = textBoxComments.Text.Trim();

            //FamilyInfo
            string coupleStatusText = EnumUtils.getEnumText(typeof(Soldier.Couple_Status), listBoxCoupleState.SelectedItem.ToString());                                                    
            s.CoupleStatus = (Soldier.Couple_Status)Enum.Parse(typeof(Soldier.Couple_Status), coupleStatusText);
            s.WifeName = textBoxWifeName.Text.Trim();
            s.ChildrenCtr = (byte)numericUpDownChildren.Value;
            s.ChildrenNames = textBoxChildrenNames.Text.Trim();

            //ArmyInfo

            //creating the qualifications list
            foreach (string check in checkedListBoxQualifications.CheckedItems)
                s.QualifiedList.Add(check);
            
            s.Position = comboBoxPosition.Text.Trim();
            s.ArrivalDate = dateTimePickerArrival.Value;
            s.Platoon = (byte)numericUpDownPlatoon.Value;
            s.ShoeSize = (byte)numericUpDownShoeSize.Value;
            string shoeStatusText = EnumUtils.getEnumText(typeof(Soldier.Shoe_Status), comboBoxShoeStatus.SelectedItem.ToString());                                                    
            s.ShoeStatus = (Soldier.Shoe_Status)Enum.Parse(typeof(Soldier.Shoe_Status), shoeStatusText);
            string idDiscStatusText = EnumUtils.getEnumText(typeof(Soldier.IdDisc_Status), comboBoxDiscStatus.SelectedItem.ToString());                                                    
            s.IdDiscStatus = (Soldier.IdDisc_Status)Enum.Parse(typeof(Soldier.IdDisc_Status), idDiscStatusText);

            if (radioButtonIsActiveNo.Checked)
                s.IsActive = false;
            else s.IsActive = true;

            //ContactInfo
            s.ContactFirstName = maskedTextBoxRelativeFirstName.Text.Trim();
            s.ContactLastName = maskedTextBoxRelativeLastName.Text.Trim();
            s.ContactHomePhone = maskedTextBoxRelativeHomePhone.Text.Trim();
            s.contactCellPhone= maskedTextBoxRelativeCellPhone.Text.Trim();
            s.ContactEmail = maskedTextBoxRelativeEmail.Text.Trim();
            string relationText = EnumUtils.getEnumText(typeof(Soldier.Relation), comboBoxRelation.SelectedItem.ToString());
            s.ContactRelation = (Soldier.Relation)Enum.Parse(typeof(Soldier.Relation), relationText);
            s.ContactAdress = maskedTextBoxRelativeAdress.Text.Trim();

            return s;

        }

        #endregion

        #region event_handlers
        private void radioButtonIsMarriedYes_CheckedChanged(object sender, EventArgs e)
        {
            textBoxWifeName.Enabled = true;
        }

        private void radioButtonIsMarriedNo_CheckedChanged(object sender, EventArgs e)
        {
            textBoxWifeName.Enabled = false;
            textBoxWifeName.Clear();
        }

        private void radioButtonIsChildrenYes_CheckedChanged(object sender, EventArgs e)
        {
            numericUpDownChildren.Enabled = true;
            textBoxChildrenNames.Enabled = true;
        }

        private void radioButtonIsChildrenNo_CheckedChanged(object sender, EventArgs e)
        {
            numericUpDownChildren.Enabled = false;
            textBoxChildrenNames.Enabled = false;
            numericUpDownChildren.Value = 0;
        }

        private void buttonClearFields_Click(object sender, EventArgs e)
        {
            DialogResult result = MessageBox.Show("?האם אתה בטוח שברצונך לאפס את השדות", "!שים לב", MessageBoxButtons.YesNo);

            if (result == DialogResult.Yes)
                sCard.createNewSoldierDataForm();
        }

        
        private void pictureBox_Click(object sender, EventArgs e)
        {
            if (pictureBox.Image !=null)
                new PictureBoxForm(pictureBox.Image, maskedTextBoxFirstName.Text, maskedTextBoxLastName.Text).ShowDialog();
        }

        private void pictureBox_MouseMove(object sender, MouseEventArgs e)
        {
            if (pictureBox.Image != null)
            {
                toolTip.Active = true;
                toolTip.SetToolTip(pictureBox, "לחץ על התמונה להגדלה");
            }
            else toolTip.Active = false;
        }

        private void buttonGo_Click(object sender, EventArgs e)
        {
            PaintWithWhiteAllFields();

            //checks that all * fields are filled and that there is no error provider.
            if (!PaintWithYellow())
            { 
                Soldier s = createSoldier();

                if (Soldier.isExists(s.ArmyID))
                {
                    //there is already a soldier with this armyID --->>> ask the user if he really want to update the data.
                    DialogResult result;
                    result = MessageBox.Show("?לוחם בעל מספר אישי זה קיים במערכת. האם ברצונך לעדכן פרטיו", "!שים לב", MessageBoxButtons.YesNo);
                    if (result == DialogResult.Yes)
                    {
                        company.addSoldier(s);
                        MessageBox.Show("הכרטיס עודכן בהצלחה",
                                        "עידכון",
                                        MessageBoxButtons.OK,
                                        MessageBoxIcon.Asterisk);
                    }
                    else MessageBox.Show(".אירעה תקלה. פרטי הלוחם לא נוספו למסד הנתונים");
                }
                else
                {
                    company.addSoldier(s);
                    MessageBox.Show("הכרטיס נשמר בהצלחה",
                                    "עידכון",
                                    MessageBoxButtons.OK,
                                    MessageBoxIcon.Asterisk);
                }

            }
            else
            {
                MessageBox.Show("בדוק את השדות המודגשים", 
                                "שגיאות בפרטים",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Asterisk);
            }
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            sCard.changeMainPanelToDefault();
        }

        private void buttonPicChoose_Click(object sender, EventArgs e)
        {
            OpenImageFileDialog dlg = new OpenImageFileDialog();
            DialogResult dlg_result;
            if ((dlg_result = dlg.ShowDialog()) == DialogResult.OK)
                pictureBox.ImageLocation = dlg.FileName;
        }

        #endregion

        private void initializeBoxesItems()
        {
            //adding to each Control its appropriate string arrays.
            listBoxCoupleState.Items.AddRange(EnumUtils.getHebDescriptionsArray(typeof(Soldier.Couple_Status)));
            comboBoxShoeStatus.Items.AddRange(EnumUtils.getHebDescriptionsArray(typeof(Soldier.Shoe_Status)));
            comboBoxDiscStatus.Items.AddRange(EnumUtils.getHebDescriptionsArray(typeof(Soldier.IdDisc_Status)));
            comboBoxRelation.Items.AddRange(EnumUtils.getHebDescriptionsArray(typeof(Soldier.Relation)));

            //setting the default state.
            listBoxCoupleState.SelectedItem = listBoxCoupleState.Items[listBoxCoupleState.Items.Count - 1];
            comboBoxShoeStatus.SelectedItem = comboBoxShoeStatus.Items[comboBoxShoeStatus.Items.Count - 1];
            comboBoxDiscStatus.SelectedItem = comboBoxDiscStatus.Items[comboBoxDiscStatus.Items.Count - 1];
            comboBoxRelation.SelectedItem = comboBoxRelation.Items[comboBoxRelation.Items.Count - 1];
        }

    }
}
